package net.loogn.stardust.server;

import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by Administrator on 2017/4/7.
 */
public class StardustFilter implements Filter {

    public final void init(FilterConfig filterConfig) throws ServletException {
        String configClass = filterConfig.getInitParameter("configClass");
        try {
            Class<?> clazz = Class.forName(configClass);
            StardustConfig config = (StardustConfig) clazz.newInstance();
            StardustService.register(config);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI().toLowerCase();
        if (url.startsWith(StardustService.getStardustRoot())) {
            //进入Stardust
            response.setCharacterEncoding("UTF-8");
            String path = url.substring(StardustService.getStardustRoot().length());

            if (path.length() == 0 || path.equals("/")) {
                response.getWriter().write("Hello Stardust!");
                response.flushBuffer();
                return;
            } else {
                String json = "";
                if (request.getContentLength() > 0) {
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    while ((len = request.getInputStream().read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    outputStream.close();
                    json = outputStream.toString("utf-8");
                }
                ActionManager.ActionWrapper actionWrapper = ActionManager.getActionWrapper(path);
                if (actionWrapper != null) {
                    try {
                        Object obj = actionWrapper.invoke(json);
                        response.setContentType("application/Json");
                        String result = JSON.toJSONString(obj);
                        response.getWriter().write(result);
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                        response.sendError(500, e.getMessage());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                        response.sendError(500, e.getMessage());
                    }
                } else {
                    response.sendError(404, "没有找到服务:" + path);
                }
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    public final void destroy() {
        StardustService.logout();
    }
}
